//
//  TLScrapView.m
//  KidReading
//
//  Created by telen on 16/5/30.
//  Copyright © 2016年 刘赞黄Telen. All rights reserved.
//

#import "TLScrapView.h"
#import "UIColor+Hex.h"
#import "UIButton+Telen.h"
#import "ViewUtils.h"
#import "TLCFunction.h"
#import "UIView+Telen.h"

#pragma mark- ScrapRectView
@interface ScrapRectView()
@property(nonatomic,assign)BOOL foucus;
@property(nonatomic,strong)void(^didTapRect)(ScrapRectView* scraprectview);
@property(nonatomic,strong)void(^didDelRect)(ScrapRectView* scraprectview);
@property(nonatomic,strong)void(^didModyRect)(ScrapRectView* scraprectview);
@end
@implementation ScrapRectView
{
    UIPanGestureRecognizer* panGesture;
    UIButton* delBtn;
    UIButton* movBtn;
}
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [[UIColor colorWithHexString:@"#5F96E3"] colorWithAlphaComponent:0.2];
        self.layer.borderWidth = 0;
        self.layer.borderColor = [[UIColor colorWithHexString:@"#5F96E3"] colorWithAlphaComponent:0.9].CGColor;
        //
        CGRect rect = CGRectMake(0, 0, 44, 44);
        delBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        delBtn.frame = rect;
        [delBtn setBackgroundImage:[UIImage imageNamed:@"scrap_delete_normal.png"] forState:UIControlStateNormal];
        [delBtn setBackgroundImage:[UIImage imageNamed:@"scrap_delete_normal.png"] forState:UIControlStateHighlighted];
        [delBtn addTouchScaleTransitions];
        delBtn.hidden = YES;
        delBtn.transform = CGAffineTransformMakeScale(0.0001, 0.0001);
        //
        movBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        movBtn.frame = rect;
        [movBtn setBackgroundImage:[UIImage imageNamed:@"scrap_move_normal.png"] forState:UIControlStateNormal];
        [movBtn setBackgroundImage:[UIImage imageNamed:@"scrap_move_normal.png"] forState:UIControlStateHighlighted];
        [movBtn addTouchScaleTransitions];
        movBtn.hidden = YES;
        movBtn.transform = CGAffineTransformMakeScale(0.0001, 0.0001);
        //
        [self addTap];
        [self addPan];
        [delBtn addTarget:self action:@selector(delSelf) forControlEvents:UIControlEventTouchUpInside];
        self.foucus = NO;
    }
    return self;
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    [self updateEditBtns];
}

- (void)setCenter:(CGPoint)center
{
    [super setCenter:center];
    [self updateEditBtns];
}

- (void)updateEditBtns
{
    if (delBtn.superview == nil && self.superview) {
        [self.superview addSubview:delBtn];
    }
    if (movBtn.superview == nil && self.superview) {
        [self.superview addSubview:movBtn];
    }
    delBtn.center = CGPointMake(self.right, self.top);
    movBtn.center = CGPointMake(self.right, self.bottom);
}

- (void)ani_Forcus:(NSNumber*)foucus
{
    if ([foucus boolValue]) {
        self.layer.borderWidth = 2;
        panGesture.enabled = YES;
        delBtn.hidden = movBtn.hidden = NO;
        [self updateEditBtns];
        delBtn.transform = CGAffineTransformMakeScale(0.0001, 0.0001);
        movBtn.transform = CGAffineTransformMakeScale(0.0001, 0.0001);
        [UIView animateWithDuration:0.1 animations:^{
            delBtn.transform = CGAffineTransformMakeScale(1, 1);
            movBtn.transform = CGAffineTransformMakeScale(1, 1);
        } completion:^(BOOL finished) {
            if (finished) {
                delBtn.transform = CGAffineTransformMakeScale(1, 1);
                movBtn.transform = CGAffineTransformMakeScale(1, 1);
            }
        }];
    }else{
        self.layer.borderWidth = 0;
        panGesture.enabled = NO;
        delBtn.hidden = movBtn.hidden = NO;
        [UIView animateWithDuration:0.1 animations:^{
            delBtn.transform = CGAffineTransformMakeScale(0.0001, 0.0001);
            movBtn.transform = CGAffineTransformMakeScale(0.0001, 0.0001);
        } completion:^(BOOL finished) {
            if (finished) {
                delBtn.hidden = movBtn.hidden = YES;
            }
        }];
    }
}

- (void)setFoucus:(BOOL)foucus
{
    _foucus = foucus;
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [self performSelector:@selector(ani_Forcus:) withObject:@(foucus) afterDelay:0.11];
}

- (void)addTap
{
    UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTap)];
    [self addGestureRecognizer:tap];
}
- (void)addPan
{
    panGesture = [self addPanGesture_CanMove];
    UIPanGestureRecognizer* pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(didDragged_Move:)];
    [movBtn addGestureRecognizer:pan];
}
- (void)didTap
{
    if (_didTapRect) {
        _didTapRect(self);
    }
}

- (void)didDragged_Move:(UIPanGestureRecognizer*)sender
{
    if (sender.state == UIGestureRecognizerStateChanged ||
        sender.state == UIGestureRecognizerStateEnded) {
        //注意，这里取得的参照坐标系是该对象的上层View的坐标。
        CGPoint offset = [sender translationInView:self.superview];
        UIView *draggableObj = sender.view;
        //通过计算偏移量来设定draggableObj的新坐标
        CGPoint pt = CGPointMake(draggableObj.center.x + offset.x, draggableObj.center.y + offset.y);
        self.frame = TLRectMakePointToPoint(pt, self.origin);
        
        //初始化sender中的坐标位置。如果不初始化，移动坐标会一直积累起来。
        [sender setTranslation:CGPointMake(0, 0) inView:self.superview];
        //
        if (_didModyRect) {
            _didModyRect(self);
        }
    }
}

- (void)delSelf
{
    if (_didDelRect) {
        _didDelRect(self);
    }
    [UIView animateWithDuration:0.3 animations:^{
        self.alpha = delBtn.alpha = movBtn.alpha = 0.01;
    } completion:^(BOOL finished) {
        [delBtn removeFromSuperview];
        [movBtn removeFromSuperview];
        [self removeFromSuperview];
    }];
}

@end




#pragma mark- TLScrapView
@implementation TLScrapView
{
    NSMutableArray* scrapRectArr;
    ScrapRectView* theScrapRectView;
    ScrapRectView* foucusScrapRectView;
    CGPoint beginPoint;
    BOOL beginPt;
}

- (void)setCanEdit:(BOOL)canEdit
{
    _canEdit = canEdit;
    [self toFoucus:nil];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        scrapRectArr = [NSMutableArray new];
        [self addTap];
    }
    return self;
}

-(void)toFoucus:(ScrapRectView*)scraprectview
{
    for (ScrapRectView* obj in scrapRectArr) {
        if (obj == scraprectview) {
            obj.foucus = YES;
        }else{
            obj.foucus = NO;
        }
    }
    foucusScrapRectView = scraprectview;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    beginPoint = point;
    beginPt = NO;
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (touches.count > 1) {
        return;
    }
    __weak TLScrapView* wself = self;
    //
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    //CGPoint ppoint = [touch previousLocationInView:self];
    if (foucusScrapRectView && CGRectContainsPoint(foucusScrapRectView.frame, point)) {
        return;
    }
    
    if (beginPt == NO) {
        CGFloat dx = fabs(point.x - beginPoint.x);
        CGFloat dy = fabs(point.y - beginPoint.y);
        if (dx + dy > 10 && dx >=2 && dy >= 2) {
            beginPt = YES;
            //beginPoint = ppoint;
            theScrapRectView = [[ScrapRectView alloc] initWithFrame:CGRectZero];
            theScrapRectView.createTime = [NSDate date];
            theScrapRectView.didTapRect = ^(ScrapRectView* scraprectview){
                [wself toFoucus:scraprectview];
            };
            theScrapRectView.didDelRect = ^(ScrapRectView* scraprectview){
                if (wself.didDelScrapRect) {
                    wself.didDelScrapRect(scraprectview);
                }
            };
            theScrapRectView.didModyRect = ^(ScrapRectView* scraprectview){
                if (wself.didModyScrapRect) {
                    wself.didModyScrapRect(scraprectview);
                }
            };
            [self addSubview:theScrapRectView];
            [scrapRectArr addObject:theScrapRectView];
            [self toFoucus:nil];
            if (self.didModyScrapRect) {
                self.didModyScrapRect(theScrapRectView);
            }
        }
    }
    if (theScrapRectView) {
        theScrapRectView.frame = TLRectMakePointToPoint(point, beginPoint);
    }
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    beginPt = NO;
    if(theScrapRectView)[self toFoucus:theScrapRectView];
    theScrapRectView.modyTime = [NSDate date];
    theScrapRectView = nil;
}

- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self touchesEnded:touches withEvent:event];
}

- (void)addTap
{
    UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTap)];
    [self addGestureRecognizer:tap];
}

- (void)didTap
{
    [self toFoucus:nil];
}

#pragma mark-
- (void)removeScrapRect:(ScrapRectView*)screct
{
    NSArray* arr = [NSArray arrayWithArray:scrapRectArr];
    for (ScrapRectView* obj in arr) {
        if (obj == screct) {
            [scrapRectArr removeObject:obj];
        }
    }
    if(screct.superview)[screct removeFromSuperview];
}
- (ScrapRectView *)addScrapRectWithRect:(CGRect)frame filePath:(NSString *)urlPath localPath:(NSString *)localPath creatTime:(NSDate*)cttime modyTime:(NSDate*)mdtime
{
    __weak TLScrapView* wself = self;
    ScrapRectView* screct = [[ScrapRectView alloc] initWithFrame:frame];
    screct.createTime = cttime;
    screct.modyTime = mdtime;
    screct.filePath = urlPath;
    screct.localPath = localPath;
    screct.didTapRect = ^(ScrapRectView* scraprectview){
        [wself toFoucus:scraprectview];
    };
    screct.didDelRect = ^(ScrapRectView* scraprectview){
        if (wself.didDelScrapRect) {
            wself.didDelScrapRect(scraprectview);
        }
    };
    screct.didModyRect = ^(ScrapRectView* scraprectview){
        if (wself.didModyScrapRect) {
            wself.didModyScrapRect(scraprectview);
        }
    };
    [self addSubview:screct];
    [scrapRectArr addObject:screct];
    return screct;
}


@end
